package io.kimmking.auth2.services.impl;

import io.kimmking.auth2.entity.SysUser;
import io.kimmking.auth2.services.AbstractUserDetailService;
import io.kimmking.dubbo.common.entity.Customer;
import io.kimmking.dubbo.common.service.CustomerService;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.Objects;

@Service
@Slf4j
public class UserDetailServiceImpl extends AbstractUserDetailService {

    @DubboReference(version = "1.0.0")
    CustomerService customerService;

    /**
     * 密码的校验方式
     */
    @Autowired
    private PasswordEncoder passwordEncoder;

    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {

        log.info("开始执行loadUserByUsername方法");
        Customer customer = customerService.selectOneCustomer(s);
        log.info("执行loadUserByUsername方法完成 " + customer);
        return getSysUser(customer);
    }


    /**
     * 将customer转化为SysUser
     * @param customer
     * @return
     */
    private SysUser getSysUser(Customer customer) {
        log.info("开始执行将customer转化为SysUser");
        SysUser sysUser = new SysUser();
        sysUser.setPassword(passwordEncoder.encode("666666"));
        BeanUtils.copyProperties(Objects.requireNonNull(customer, "User is null from getUserByUserName"),
                sysUser);
        return sysUser;
    }
}
